<template>
  <div class="main">
    <!-- 提示信息 -->
    <el-text
      size="small"
      :type="rawInput.length ? (showError ? 'danger' : 'success') : 'info'"
      class="vibrate-fast-hard-once"
    >
      {{
        rawInput.length
          ? showError
            ? errorMsg
            : field.flightNumber +
              `${
                field.crewIntention == "ALT"
                  ? " 备降 " + field.diversionAirport
                  : " 返航"
              }`
          : '填写示例: "CCA101 ZLXY" 或 "CCA102 RTN"'
      }}
    </el-text>
    <!-- 简易输入框 -->
    <el-input
      class="main-input"
      v-model="rawInput"
      @input="handlelInput"
      @keyup.enter="handleEnter"
      clearable
      placeholder=""
    ></el-input>
    <!-- 复杂输入框 -->
    <el-collapse>
      <el-collapse-item title="更多信息（选填）">
        <el-form label-width="90px" size="small" v-if="field">
          <el-form-item label="日期 (PEK)">
            <el-date-picker
              v-model="field.eventDate"
              type="date"
              format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="时间 (PEK)">
            <el-time-picker
              v-model="field.origionTime"
              format="HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="航班号">
            <el-input
              v-model="field.flightNumber"
              @input="handleInputFlightNumber"
              maxlength="9"
              style="width: 100%"
              placeholder=""
            />
          </el-form-item>
          <el-form-item label="起飞机场">
            <el-input
              v-model="field.departureAirport"
              @input="handleInputDepartureAirport"
              maxlength="4"
              style="width: 100%"
              placeholder=""
            />
          </el-form-item>
          <el-form-item label="目的地机场">
            <el-input
              v-model="field.destinationAirport"
              @input="handleInputDestinationAirport"
              maxlength="4"
              style="width: 100%"
              placeholder=""
            />
          </el-form-item>
          <el-form-item label="机组意图">
            <el-radio-group
              v-model="field.crewIntention"
              @change="handleChangeCrewIntention"
            >
              <el-radio value="ALT">备降</el-radio>
              <el-radio value="RTN">返航</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            :label="`${field.crewIntention == 'ALT' ? '备降' : '返航'}原因`"
          >
            <el-select v-model="field.eventReason" style="width: 100%">
              <el-option value="天气">天气</el-option>
              <el-option value="故障">故障</el-option>
              <el-option value="旅客">旅客</el-option>
              <el-option value="其他">其他</el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            :label="`紧急${field.crewIntention == 'ALT' ? '备降' : '返航'}`"
          >
            <el-radio-group v-model="field.isEmergency">
              <el-radio :value="0">否</el-radio>
              <el-radio :value="1">是</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="备降机场">
            <el-input
              v-model="field.diversionAirport"
              @input="handleInputDiversionAirport"
              maxlength="4"
              style="width: 100%"
              placeholder=""
              :disabled="field.crewIntention != 'ALT'"
            />
          </el-form-item>

          <el-form-item label="计划备降场">
            <el-radio-group
              v-model="field.isPlannedDiversionAirport"
              :disabled="field.crewIntention != 'ALT'"
            >
              <el-radio :value="1">是</el-radio>
              <el-radio :value="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" @click="handleSubmit">提交</el-button>
            <el-button type="primary" link @click="newField">清空</el-button>
          </el-form-item>
        </el-form>
        <!-- <pre>{{ JSON.stringify(field, null, 2) }}</pre> -->
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted } from "vue";
// import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
// import axios from "axios";
// import dayjs from "dayjs";
import useSeatStore from "@/store/seat.js";
// import useJournalStore from "@/store/journal.js";
import * as inputHandler from "./inputHandler.js";
// import handleSave from "./handleSave.js";
// import handleQuery from "./handleQuery.js";
import handleUpdateItem from "./handleUpdateItem.js";

const seatStore = useSeatStore();
// const journalStore = useJournalStore();

// const isLoading = computed(
//   () => journalStore.diversionShareStatus.isToolboxLoading
// );

const field = ref();
const rawInput = ref("");

const newField = () => {
  rawInput.value = "";
  let val = {
    number: null,
    eventDate: new Date(), // 事件日期
    flightNumber: "", // 航班号
    departureAirport: "", // 原起飞机场
    destinationAirport: "", // 原目落地机场
    diversionAirport: "", // 备降机场
    crewIntention: "ALT", // 机组意图 (ALT/RTN)
    eventReason: "天气", // 备降原因 (天气/故障/旅客/其他)
    isEmergency: 0, // 是否为紧急情况 (0/1)
    origionSeatIP: seatStore.currentSeat.ip, // 初始席位IP地址 (string)
    origionSeatName: seatStore.currentSeat.seatName, // 初始席位名称 (null/string)
    origionSeatUser: seatStore.currentSeatData
      ? seatStore.currentSeatData.users.map((u) => u.userName).join(", ")
      : "未知", // 初始席位协调席管制员 (null/array)
    origionTime: new Date(), // 初始席位录入时间 (null/datetime)
    aircraftType: "", // 航空器机型
    isPlannedDiversionAirport: 1, // 是否为计划内的备降场
    reportPlan: 0, // 是否报告计划室 (0/1)
    reportPlanSeatIP: "", // 报告计划室席位IP (null/string)
    reportPlanSeatName: "", // 报告计划室席位名称 (null/string)
    reportPlanSeatUser: "", // 报告计划室席位协调席管制员 (null/array)
    reportPlanTime: null, // 报告计划室时间 (null/datetime)
    reportFlow: 0, // 是否报告ACCFlow (0/1)
    reportFlowSeatIP: "", // 报告ACCFlow席位IP (null/string)
    reportFlowSeatName: "", // 报告ACCFlow席位名称 (null/string)
    reportFlowSeatUser: "", // 报告ACCFlow席位协调席人员 (null/array)
    reportFlowTime: null, // 报告ACCFlow时间(null/datetime)
    setDisposed: 0, //删除记录
    setDisposedSeatIP: "", // 删除记录席位IP (null/string)
    setDisposedSeatName: "", // 删除记录席位名称 (null/string)
    setDisposedSeatUser: "", // 删除记录席位协调席人员 (null/array)
    setDisposedTime: null, // 删除记录时间(null/datetime)
  };
  field.value = JSON.parse(JSON.stringify(val));
};

const handlelInput = (value) => {
  // 过滤非字母、数字和空格的字符，并将字母转为大写
  rawInput.value = inputHandler.upperLetterNumberAndSpace(value);
  errorMsg.value = "";
  showError.value = false;
  handleContentCheck();
};

const handleContentCheck = () => {
  if (rawInput.value.length < 9) {
    handleShowError("输入的字符长度不够");
    return false;
  }
  let content = rawInput.value.split(" ");
  if (content.length != 2) {
    handleShowError("格式不正确");
    return false;
  }
  if (content[1] != "RTN" && content[1].length != 4) {
    handleShowError("备降机场不正确");
    return false;
  }

  // 如果输入的数据格式正确，修改表单内容
  field.value.flightNumber = content[0];
  if (content[1] == "RTN") {
    field.value.diversionAirport = "";
    field.value.crewIntention = "RTN";
  } else {
    field.value.diversionAirport = content[1];
    field.value.crewIntention = "ALT";
  }
  return true;
};

const handleEnter = () => {
  // 提交内容
  handleSubmit();
};

const handleSubmit = () => {
  if (!handleContentCheck()) return;
  handleUpdateItem(field.value)
    .then(() => {
      newField();
    })
    .catch(() => {});
};

const handleChangeCrewIntention = (value) => {
  if (value == "RTN") {
    field.value.diversionAirport = field.value.destinationAirport;
  } else if (value == "ALT") {
    if (field.value.diversionAirport == field.value.destinationAirport) {
      field.value.diversionAirport = "";
    }
  }
  field.value.isPlannedDiversionAirport = 1;
};

const handleInputFlightNumber = (value) => {
  // 航班号：只允许输入数字和字母
  field.value.flightNumber = inputHandler.upperLetterAndNumber(value);
};

const handleInputDepartureAirport = (value) => {
  // 起飞机场：只允许输入字母
  field.value.departureAirport = inputHandler.upperLetterOnly(value);
};

const handleInputDestinationAirport = (value) => {
  // 只目的地机场：允许输入字母
  field.value.destinationAirport = inputHandler.upperLetterOnly(value);
};

const handleInputDiversionAirport = (value) => {
  // 备降机场：只允许输入字母
  field.value.diversionAirport = inputHandler.upperLetterOnly(value);
};

const showError = ref(false);
const errorMsg = ref("");
const handleShowError = (msg) => {
  if (msg.length == 0) return;
  errorMsg.value = msg;
  showError.value = true;
};

onMounted(() => {
  newField();
});
</script>

<style lang="css" scoped>
@import "@/styles/vibrate.css";

.main-input {
  margin: 12px 0;
  font-size: 32px;
  height: 48px;
}
</style>
